<?php
/*
 * @Author: 李明
 * @Date: 2021-08-10 17:45:13
 * @LastEditTime: 2022-01-21 18:01:17
 * @LastEditors: 李明
 * @Description:
 * @FilePath: /CRM2.0-PHP/app/Http/Controllers/admin/UserController.php
 * @山东壹零贰肆信息科技有限公司
 */

namespace App\Http\Controllers\admin;

use App\Http\Controllers\common\CommonFun;
use App\Http\Controllers\common\LMReturn;
use App\Http\Controllers\Controller;
use App\Http\Resources\User as ResourcesUser;
use App\Models\Image;
use App\Models\User;
use App\Models\Worker;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Utils;

class UserController extends Controller
{
    /**
     * @description: 后台管理员添加客户
     * @param {Request} $request
     * @return {*}
     */
    public function ClientSave(Request $request)
    {
        //去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        $operation_id = $tokenInfo['worker_id'];
        // 接收参数
        try {
            $all = $request->all();
            $user = isset($all['id']) ? User::find($all['id']) : new User();
            $order_list = $user->orders->whereIn('order_status', [3, 4, 6, 8])->all() ?? [];
            $address = $all['address'];
            $area_code = $all['area_code'];
            $city_code = $all['city_code'];
            $pro_code = $all['pro_code'];
            $contact_manner = $all['contact_manner'];
            $email = $all['email'] ?? '';
            $id_number = $all['id_number'];
            $id_type = $all['id_type'];
            $name = $all['name'];
            $sex = $all['sex'];
            $account = $all['account'];
            $is_change = isset($all['id']);
            $user_list = User::where("account", $account)->get();
            if ($is_change) { // 如果是修改，需要先判断 是否已存在一样的账号
                if (count($user_list) == 1) {
                    if ($user_list[0]->id != $all['id']) {
                        return LMReturn::Error('存在重复账号，禁止修改', 'UCCS1');
                    }
                } elseif (count($user_list) > 1) {
                    return LMReturn::Error('不应该出现这种问题', 'UCCS2');
                }
            } else { // 如果是增加，需要先判断 是否已存在该账号
                if (count($user_list) > 0) {
                    return LMReturn::Error('账号已存在', 'UCCS3');
                }
            }
            $birthday = $all['birthday'];
            $image_ids = $all['image_ids'] ?? [];
            $worker_id = isset($all['worker_id']) ? $all['worker_id'] : $tokenInfo['worker_id'];
            if (count($order_list) > 0) {
                if ($contact_manner != $user['contact_manner'] || $id_number != $user['id_number'] || $id_type != $user['id_type'] || $worker_id != $user['worker_id'] || $name != $user['name'] || $sex != $user['sex']) {
                    return LMReturn::Error('此客户已产生订单，请点击修改审核', 'UC007');
                }
            }
            $worker = Worker::find($worker_id);
            $branch_id = $worker->branches ? $worker->branches->first()->id : '';
            $icon_url = $sex == '1' ? 'https://api.guoyikonggu.com/images/nan.png' : 'https://api.guoyikonggu.com/images/nv.png';
        } catch (\Throwable $th) {
            return LMReturn::Error('传参出现错误，错误代码', 'UC001');
        }
        // 入库
        try {
            if (!isset($all['id'])) {
                $this_user = User::where('id_number', $id_number)
                    ->where('id_type', $id_type)
                    ->first();
                if ($this_user) {
                    $xcx_open_id = $this_user->xcx_open_id;
                    $unionid = $this_user->unionid;
                    $public_open_id = $this_user->public_open_id;
                    $is_receive = $this_user->is_receive;
                }
            }
            DB::beginTransaction(); //开启事务
            $user->address = $address;
            $user->area_code = $area_code;
            $user->city_code = $city_code;
            $user->pro_code = $pro_code;
            $user->contact_manner = $contact_manner;
            $user->email = $email;
            $user->id_number = $id_number;
            $user->id_type = $id_type;
            $user->name = $name;
            $user->sex = $sex;
            $user->icon = $icon_url;
            $user->worker_id = $worker_id;
            $user->branch_id = $branch_id;
            $user->account = $account;
            $user->birthday = $birthday;
            $user->xcx_open_id = $xcx_open_id ?? null;
            $user->unionid = $unionid ?? null;
            $user->public_open_id = $public_open_id ?? null;
            $user->is_receive = $is_receive ?? null;
            $password = substr($id_number, -6) ?? '';
            if ($password  == '') {
                return LMReturn::Error('客户身份证号存在问题');
            } else {
                $password = CommonFun::md5($password);
                $user->password = $password;
            }
            $user->save();
            DB::commit(); //提交至数据库
        } catch (\Throwable $th) {
            DB::rollback(); //数据库回滚
            return LMReturn::Error('添加修改出现错误，错误代码', 'UC003');
        }
        // 如果返回false，则是修改时报错，数据库回滚，返回错误信息
        if (!Utils::UpImage($image_ids, $user->images, $user->id, 2, $operation_id)) {
            return LMReturn::Error('添加修改图片出现错误其他信息已提交，请重新上传图片', 'UC002');
        }
        return LMReturn::Success($user);
    }
    /**
     * @description: 客户列表
     * @param {Request} $request
     * @return {*}
     */
    public function UserList(Request $request)
    {
        //去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        //接收前端传递过来的值
        try {
            $all = $request->all();
            $branch_id = $all['branch_id'] ?? '';
            $worker_id = $all['worker_id'] ?? '';
            $login_worker_id = $tokenInfo['worker_id'];
        } catch (\Throwable $th) {
            return LMReturn::Error('处理参数时发生错误，请联系管理员', 'UC005');
        }
        // 处理参数
        try {
            $where = [];
            $bmidList = BranchController::queryBranchToWorkerID($login_worker_id, $branch_id);
            if ($worker_id != '') {
                $where[] = ['wroker_id', $worker_id];
            }
        } catch (\Throwable $th) {
            return LMReturn::Error('处理参数时发生错误，请联系管理员', 'UC006');
        }
        // 数据库操作
        try {
            $pageSize = $all['size'] ?? 15;
            $user_list = User::where($where)
                ->with('bank_cards')
                ->with('bank_cards.bank')
                ->with('worker')
                ->with('branch')
                ->when(count($bmidList) > 0, function ($query) use ($bmidList) {
                    return $query->whereIn('branch_id', $bmidList);
                })
                ->orderBy("update_time", "desc")
                ->paginate($pageSize);
            $data_user_list = json_decode(json_encode($user_list), true);
            $return_datas['current_page'] = $data_user_list['current_page'];
            $return_datas['from'] = $data_user_list['from'];
            $return_datas['last_page'] =  $data_user_list['last_page'];
            $return_datas['per_page'] = $data_user_list['per_page'];
            $return_datas['to'] = $data_user_list['to'];
            $return_datas['total'] = $data_user_list['total'];
            return LMReturn::Success($user_list);
        } catch (\Throwable $th) {
            return LMReturn::Error('处理参数时发生错误，请联系管理员', 'UC004');
        }
    }
    /**
     * @description: 客户管理列表(包括公海的和待分配的)
     * @param {Request} $request
     * @return {*}
     */
    public function ClientManagementList(Request $request)
    {
        //去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        //接收前端传递过来的值
        $all = $request->all();
        $where = [];
        $type = $all['type'] ?? 2;
        if (isset($all['user_type'])) {
            $where[] = ['user.user_type', $all['user_type']];
        }
        if (isset($all['worker_id'])) //如果传了员工id 返回这个员工的
        {
            $where[] = ['user.worker_id', $all['worker_id']];
        }
        if (isset($all['pro_code'])) {
            $where[] = ['user.pro_code', $all['pro_code']];
        }
        if (isset($all['city_code'])) {
            $where[] = ['user.city_code', $all['city_code']];
        }
        if (isset($all['area_code'])) {
            $where[] = ['user.area_code', $all['area_code']];
        }

        if (isset($all['sex'])) // 性别筛选
        {
            $where[] = ['user.sex', $all['sex']];
        }
        if (isset($all['name'])) //姓名筛选
        {
            $searchName = $all['name'];
            $where[] = ['user.name', 'like', '%' . $searchName . '%'];
        }
        if (isset($all['contact_manner'])) //联系方式筛选
        {
            $contact_manner = $all['contact_manner'];
            $where[] = ['user.contact_manner', 'like', '%' . $contact_manner . '%'];
        }
        $tag_id_arr = [];
        if (isset($all['tag_id'])) // 标签筛选  是个数组
        {
            $tag_id_arr = $all['tag_id'];
        }
        if (isset($all['user_status'])) {
            $where[] = ['user.user_status', $all['user_status']];
        }

        // 员工信息
        $worker_id = $tokenInfo['worker_id'];
        if ($type == 1) {
            $bmidList = [];
        } else {
            // 基础部门信息
            if (isset($all['manage_bm'])) {
                $bmidList = BranchController::queryBranchToWorkerID($worker_id, $all['manage_bm']);
            } else {
                $bmidList = BranchController::queryBranchToWorkerID($worker_id);
            }
        }
        if (count($bmidList) == 0) {
            $where[] = ['user.worker_id', $tokenInfo['worker_id']];
        }
        if (isset($all['branch_id'])) {
            $where[] = ['user.branch_id', $all['branch_id']];
        }
        $pageSize = $all['size'] ?? 15;
        $user_list = User::where($where)
            ->with('bank_cards')
            ->with('bank_cards.bank')
            ->with('worker')
            ->with('branch')
            ->with('pro')
            ->with('city')
            ->with('area')
            ->with('tags')
            ->with('orders')
            ->with('images')
            ->when(count($bmidList) > 0, function ($query) use ($bmidList) {
                return $query->whereIn('user.branch_id', $bmidList);
            })
            ->when(count($tag_id_arr) > 0, function ($big_query) use ($tag_id_arr) {
                return $big_query->whereHas(
                    'tags',
                    function ($query) use ($tag_id_arr) {
                        $query->whereIn('tag_id', $tag_id_arr);
                    }
                );
            })

            // ->whereHas('tags', function ($query) use ($tag_id_arr) {
            //   return $query->whereIn('id', $tag_id_arr);
            // })
            ->orderBy("user.update_time", "desc")
            ->paginate($pageSize);
        $res_list = ResourcesUser::collection($user_list);
        $res_data = Utils::deal_page_resources($res_list, $user_list);
        return LMReturn::Success($res_data);
    }
    /**
     * @description:
     * @param {*}
     * @return {*}
     */
    //员工删除(真删除)
    public function UserDelete(Request $request)
    {
        try {
            //去验证token值
            $tokenInfo = json_decode($this->verifyTokenLm(), true);
            //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
            if ($tokenInfo['code'] == 400) {
                return LMReturn::Error($tokenInfo['msg'], 'UCUD2');
            }
            //接收前端传递过来的值
            $all = $request->all();
            $user_id = $all['id'];
        } catch (\Throwable $th) {
            //throw $th;
        }
        try {
            $user = User::find($user_id);
            if (count($user->orders) > 0) {
                return LMReturn::Error('无法删除，存在订单', 'UCUD4');
            }
            if (count($user->bank_cards) > 0) {
                return LMReturn::Error('无法删除，请先删除银行卡', 'UCUD1');
            }
            $user->delete();
            return LMReturn::Success($user, '客户已删除');
        } catch (\Throwable $th) {
            return LMReturn::Error('删除失败，请联系技术支持', 'UCUD3');
        }
    }
    /**
     * @description: 处理，合并，有问题的数据，不仅仅是删除
     * @param {Request} $request
     * @return {*}
     */
    public function testUserDelete(Request $request)
    {
        $dul = [];
        $dbl = [];
        DB::beginTransaction(); // 开启数据库事务
        foreach (User::all() as $user) {
            if (count($user->orders) > 0) { // 去处理同名的问题
                // return LMReturn::Error('无法删除，存在订单', 'UCUD4');
                $id_number = $user->id_number;
                if ($id_number != '' && $id_number != Null) {
                    $user_list = User::where('id_number', $id_number)->get();
                    foreach ($user_list as $u) {
                        if ($u->remark != '该用户由系统自动生成，请完善其他信息') {
                            continue;
                        }
                        if (count($u->images) > 0) {
                            continue;
                        }
                        if (count($u->reocrd_images) > 0) {
                            continue;
                        }
                        if ($user->id == $u->id) {
                            continue;
                        }
                        $u_orders = $u->orders;
                        if (count($u_orders) > 0) {
                            continue;
                        }

                        $u_bank_cards = $u->bank_cards;
                        $is_have_bank_card_images = false;
                        if (count($u_bank_cards) > 0) { // 如果有银行卡，判断有没有图片，有图片不能删
                            foreach ($u_bank_cards as $bank_card) {
                                if (count($bank_card->images) > 0) {
                                    $is_have_bank_card_images = true;
                                }
                            }
                        }
                        if ($is_have_bank_card_images) {
                            continue;
                        }
                        // 这个时候剩下的用户就可以删掉了，但是要一起删除银行卡
                        foreach ($u_bank_cards as $bank_card) {
                            $bank_card->delete();
                            $dbl[] = $bank_card;
                        }
                        $u->delete();
                        $dul[] = $u;
                    }
                }
                continue;
            }
        }
        DB::commit();
        return LMReturn::Success($dul, '客户已删除');
    }
    /**
     * @description: 删除什么都没有的垃圾数据
     * @param {Request} $request
     * @return {*}
     */
    public function testUserDeleteLaji(Request $request)
    {
        $dul = [];
        DB::beginTransaction(); // 开启数据库事务
        $user_list = User::all();
        foreach ($user_list as $user) {
            if (count($user->orders) > 0) {
                continue;
            }
            if (count($user->bank_cards) > 0) {
                continue;
            }
            if (count($user->images) > 0) {
                continue;
            }
            if (count($user->reocrd_images) > 0) {
                continue;
            }
            if ($user->remark != '该用户由系统自动生成，请完善其他信息') {
                continue;
            }
            $user->delete();
            $dul[] = $user;
        }
        DB::commit();
        return LMReturn::Success($dul, '客户已删除');
    }
}
